from selenium.webdriver import Edge
from selenium.webdriver.common.by import By
import time
import csv


def drop_down():
    """执行页面向下滚动的操作"""
    for x in range(1, 12, 2):
        time.sleep(1)
        j = x / 9
        js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j
        web.execute_script(js)


# with open('苏宁.csv', mode='a', encoding='utf-8', newline='') as f:
#         csv_writer = csv.writer(f)
#         csv_writer.writerow(['title', 'price', 'evaluate', 'store_stock', 'datali_url'])


web = Edge(executable_path='../203 手机壁纸/msedgedriver.exe')
web.get('https://search.suning.com/%E8%8C%85%E5%8F%B0/')
# https://search.suning.com/%E8%8C%85%E5%8F%B0/#second-filter
# https://search.suning.com/%E8%8C%85%E5%8F%B0/#second-filter

web.implicitly_wait(5)  # 隐式等待
drop_down()


def get_next():
    # 获取数据
    divs = web.find_elements(By.CSS_SELECTOR, '.item-bg')
    for div in divs:
        # 标题
        title = div.find_element(By.CSS_SELECTOR, '.title-selling-point a').text
        # 价格
        price = div.find_element(By.CSS_SELECTOR, '.price-box').text
        price = price.replace('到手价', '')
        # 评价
        evaluate = div.find_element(By.CSS_SELECTOR, '.info-evaluate a').text
        # 店铺名
        store_stock = div.find_element(By.CSS_SELECTOR, '.store-stock a').text
        # 详情页连接
        # get_attribute 获取属性值
        datali_url = div.find_element(By.CSS_SELECTOR, '.img-block a').get_attribute('href')
        print(title, price, evaluate, store_stock, datali_url)

        # 保存数据
        with open('苏宁.csv', mode='a', encoding='utf-8', newline='') as f:
            csv_writer = csv.writer(f)
            csv_writer.writerow([title, price, evaluate, store_stock, datali_url])
